import {
  addMeetingRoom,
  queryMeetingRoom,
  updateMeetingRoom,
  deleteMeetingRoom,
} from '../services/MeetingRoomApi';

export default {
  namespace: 'meetingRoom',

  state: {
    loading: false,
    response: {},
  },

  effects: {
    *add({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(addMeetingRoom, payload);
      yield put({
        type: 'loadResponse',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) {
        callback(response);
      }
    },
    *fetch({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(queryMeetingRoom, payload);
      yield put({
        type: 'loadResponse',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) {
        callback(response);
      }
    },
    *update({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(updateMeetingRoom, payload);
      yield put({
        type: 'loadResponse',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (callback) {
        callback(response);
      }
    },
    *delete({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(deleteMeetingRoom, payload);
      yield put({
        type: 'loadResponse',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) {
        console.log('call remove callback');
        callback(response);
      }
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
    loadResponse(state, { payload }) {
      return {
        ...state,
        response: payload,
      };
    },
  },
};
